package com.inspur.fileupload.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@Controller
public class FileController {
	
	@Value("${ecweb.filetype}")
	private String fileType;
	
	@Value("${ecweb.filepath}")
	private String serverfilePath;

	 	@RequestMapping(value = "/file/upload")
	    @ResponseBody
	    public void upload(@RequestParam("vendCertificate") MultipartFile file,@RequestParam("VEND_ID")String vendId) {
	 		System.err.println("begin upload");
	 		
	 		if (file.isEmpty()) {
//	            return "file is null";
	        }
	        // 获取文件名
	        String fileName = file.getOriginalFilename();
	        // 获取文件的后缀名
	        String suffixName = fileName.substring(fileName.lastIndexOf("."));
	        // 文件上传后的路径
	        String filePath = serverfilePath+vendId+"//";
	        //删除已存在的同名文件
	        String existe=getFilePath(filePath, vendId);
	        if(existe!=null) {
	        	File file2=new File(filePath+vendId + suffixName);
	        	file2.deleteOnExit();
	        }
	        File dest = new File(filePath);
	        // 检测是否存在目录
	        if (!dest.exists()) {
	            dest.mkdirs();
	        }
	        try {
	            byte[] bytes = file.getBytes();
	            Path path = Paths.get(filePath+vendId + suffixName);
	            Files.write(path, bytes);
//	            return "上传成功";
	        } catch (IllegalStateException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
//	        return "上传失败";
	    }

	    //文件下载相关代码
	    @RequestMapping("/download/{vendId}")
	    @ResponseBody
	    public String downloadFile(HttpServletRequest request, HttpServletResponse response,@PathVariable String vendId){
	        String realPath = 
	        		serverfilePath+vendId+"//";
	        System.out.println("begin download");
	       String fileName= getFilePath(realPath,vendId);
	        if (fileName != null) {
	            File file = new File(realPath+fileName);
	            if (file.exists()) {
	                response.setContentType("application/force-download");// 设置强制下载不打开
	                response.addHeader("Content-Disposition",
	                        "attachment;fileName=" +  fileName);// 设置文件名
	                byte[] buffer = new byte[1024];
	                FileInputStream fis = null;
	                BufferedInputStream bis = null;
	                try {
	                    fis = new FileInputStream(file);
	                    bis = new BufferedInputStream(fis);
	                    OutputStream os = response.getOutputStream();
	                    int i = bis.read(buffer);
	                    while (i != -1) {
	                        os.write(buffer, 0, i);
	                        i = bis.read(buffer);
	                    }
	                    
	                    os.flush();
	                } catch (Exception e) {
	                    e.printStackTrace();
	                } finally {
	                    if (bis != null) {
	                        try {
	                            bis.close();
	                        } catch (IOException e) {
	                            e.printStackTrace();
	                        }
	                    }
	                    if (fis != null) {
	                        try {
	                            fis.close();
	                        } catch (IOException e) {
	                            e.printStackTrace();
	                        }
	                    }
	                }
	            }
	        }else {
		        return "未上传相关附件";
			}
	        return null;
	    }
	  //文件下载相关代码
	    @RequestMapping("/file/download/{vendId}")
	    @ResponseBody
	    public String downloadZipFile(HttpServletRequest request, HttpServletResponse response,@PathVariable String vendId){
	        String realPath = 
	        		serverfilePath+vendId+"//";
	        System.out.println("begin download");
	       String fileName= getFilePath(realPath,vendId+fileType);
	        if (fileName != null) {
	            File file = new File(realPath+fileName);
	            if (file.exists()) {
	                response.setContentType("application/force-download");// 设置强制下载不打开
	                response.addHeader("Content-Disposition",
	                        "attachment;fileName=" +  fileName);// 设置文件名
	                byte[] buffer = new byte[1024];
	                FileInputStream fis = null;
	                BufferedInputStream bis = null;
	                try {
	                    fis = new FileInputStream(file);
	                    bis = new BufferedInputStream(fis);
	                    OutputStream os = response.getOutputStream();
	                    int i = bis.read(buffer);
	                    while (i != -1) {
	                        os.write(buffer, 0, i);
	                        i = bis.read(buffer);
	                    }
	                    
	                    os.flush();
	                } catch (Exception e) {
	                    e.printStackTrace();
	                } finally {
	                    if (bis != null) {
	                        try {
	                            bis.close();
	                        } catch (IOException e) {
	                            e.printStackTrace();
	                        }
	                    }
	                    if (fis != null) {
	                        try {
	                            fis.close();
	                        } catch (IOException e) {
	                            e.printStackTrace();
	                        }
	                    }
	                }
	            }
	        }else {
		        return "未上传相关附件";
			}
	        return null;
	    }
	    
	    //多文件上传
	    @RequestMapping(value = "/file/batchupload", method = RequestMethod.POST)
	    @ResponseBody
	    public void handleFileUpload(HttpServletRequest request,@RequestParam("VEND_ID")String vendId) {
	        List<MultipartFile> files = ((MultipartHttpServletRequest) request)
	                .getFiles("vendCertificate");
	        String filePath = serverfilePath+vendId+"//";
	        File dest = new File(filePath);
	        if (!dest.exists()) {
	            dest.mkdirs();
	        }
	       try {
			zipFile(files, vendId);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    }
	    
	    
	    public void zipFile(List<MultipartFile> files,String vendId) throws IOException {
	    	File fileOut=new File(serverfilePath+vendId+"/"+vendId+fileType);//指定输出位置
			FileOutputStream fileOutputStream=new FileOutputStream(fileOut);//以流的形式输出
	    	ZipOutputStream zipOut=new ZipOutputStream(fileOutputStream);//注入到Zip中，以Zip的形式输出		
	    	//在压缩文件中创建文件实体		
	    	 MultipartFile file = null;
		     for (int i = 0; i < files.size(); ++i) {
		            file = files.get(i);
			    	ZipEntry entry=new ZipEntry(file.getOriginalFilename());
			    	zipOut.putNextEntry(entry);		
			    	byte[] bytes = file.getBytes();
			    	zipOut.write(bytes);
		        }
	    	//将数组中的数据注入到ZipOutputStream中		
		     zipOut.closeEntry();
		     zipOut.close();
			fileOutputStream.close();
	    }
	    
	    
	    
	    private String getFilePath(String parentPath,String findName) {
	    	String path=null;

	    	File file = new File(parentPath);
	    	File[] files = file.listFiles();
	    	if(files==null||files.length<=0) {
	    		return path;
	    	}
	    	for (File child : files) {
                if (!child.isDirectory()) {
                    String name=child.getName();
                    if(name.contains(findName)) {
                    	return name;
                    }
                }
            }
	    	return path;
	    }
}
